using System;

namespace Brilliance
{
    public class ViewFactory : IViewFactory
    {
        private readonly ActiveViewsDictionary activeViews;

        public ViewFactory()
        {
            activeViews = new ActiveViewsDictionary();
        }

        public T GetView<T>() where T : IView, new()
        {
            IView view;
            bool viewActive = activeViews.TryGetValue(typeof (T), out view);

            if (!viewActive)
            {
                view = CreateView<T>();
                activeViews.Add(typeof (T), view);
            }

            return (T) view;
        }

        private T CreateView<T>() where T : IView, new()
        {
            return new T();
        }

        public void CloseAllExceptView(Type dontCloseThisTypeOfView)
        {
            activeViews.CloseAllExceptView(dontCloseThisTypeOfView);
        }

        public bool IsViewVisible<ViewType>()
        {
            IView view;
            return activeViews.TryGetValue(typeof (ViewType), out view);
        }

        public T GetNewView<T>() where T : IView, new()
        {
            IView view;
            var viewExists = activeViews.TryGetValue(typeof (T), out view);
            if (viewExists)
            {
                view.CloseView();
            }

            view = CreateView<T>();
            activeViews.Add(typeof (T), view);

            return (T) view;
        }
    }
}